package com.vinda.ucvcamera.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.SurfaceTexture;
import android.hardware.usb.UsbDevice;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.serenegiant.usb.DeviceFilter;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.UVCCamera;
import com.serenegiant.usbcameracommon.UVCCameraHandler;
import com.serenegiant.usbcameracommon.UvcCameraDataCallBack;
import com.serenegiant.widget.CameraViewInterface;
import com.serenegiant.widget.UVCCameraTextureView;
import com.vinda.ucvcamera.MainActivity;
import com.yuan.camera.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/2/9 0009.
 * E-Mail：543441727@qq.com
 */

public class WindowService extends Service{
    private final String TAG = this.getClass().getSimpleName();

    private WindowManager.LayoutParams wmParams;
    private WindowManager mWindowManager;
    private View mWindowView;
    private LinearLayout frameCamer;
    private Button button_end;

    private int mStartX;
    private int mStartY;
    private int mEndX;
    private int mEndY;


    private static final float[] BANDWIDTH_FACTORS = {0.5f, 0.5f};
    protected USBMonitor mUSBMonitor;
    private List<UsbDevice> deviceList;
    private CameraViewInterface mUVCCameraViewFirst;
    private UVCCameraHandler mHandlerFirst;

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化windos对象
        //1,获取系统级别的WindowManager
        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        wmParams = new WindowManager.LayoutParams();
        //2,添加系统参数，确保悬浮框能显示到手机上
        //电话窗口。它用于电话交互（特别是呼入）。它置于所有应用程序之上，状态栏之下。
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        //期望的位图格式。默认为不透明
        wmParams.format = PixelFormat.TRANSLUCENT;
        //不许获得焦点
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }
        //窗口停靠位置
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;


        //放入布局
        mWindowView = LayoutInflater.from(getApplication()).inflate(R.layout.layout_window, null);
        frameCamer = mWindowView.findViewById(R.id.frameCamer);
        button_end = mWindowView.findViewById(R.id.button_end);
        TextView text_context = mWindowView.findViewById(R.id.text_context);
        mUVCCameraViewFirst = mWindowView.findViewById(R.id.camera_view_first);

        ImageButton mCaptureButtonFirst = (ImageButton) mWindowView.findViewById(R.id.capture_button_first);
        //设置显示宽高
        mUVCCameraViewFirst.setAspectRatio(UVCCamera.DEFAULT_PREVIEW_WIDTH / (float) UVCCamera.DEFAULT_PREVIEW_HEIGHT);
        ((UVCCameraTextureView) mUVCCameraViewFirst).setOnClickListener(v -> {
            dataCallback.dataChanged(mUVCCameraViewFirst);
        });

        //监听Usb设备
        if (mUSBMonitor == null)
            try {
                mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);
            } catch (final ClassCastException e) {
            } catch (final NullPointerException e) {
            }
        mUSBMonitor.register();

        mHandlerFirst = UVCCameraHandler.createHandler(this, mUVCCameraViewFirst
                , UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT
                , BANDWIDTH_FACTORS[0], new UvcCameraDataCallBack() {
                    @Override
                    public void getData(byte[] data) {
                        Log.v("zdl", "数据回调:" + data.length);
                    }
                });


        mWindowView.findViewById(R.id.button_dialog).setOnClickListener(v -> {
            final List<DeviceFilter> filter = DeviceFilter.getDeviceFilters(WindowService.this, R.xml.device_filter);
            deviceList = mUSBMonitor.getDeviceList(filter.get(0));
            List<String> list = new ArrayList<>();
            String str = "";
            if (deviceList != null && deviceList.size() != 0) {
                for (int i = 0; i < deviceList.size(); i++) {
                    list.add(String.format("UVC Camera:(%x:%x:%s)", deviceList.get(i).getVendorId(), deviceList.get(i).getProductId(), deviceList.get(i).getDeviceName()));
                    str = str + "\n" + String.format("UVC Camera:(%x:%x:%s)", deviceList.get(i).getVendorId(), deviceList.get(i).getProductId(), deviceList.get(i).getDeviceName());
                }
                text_context.setText(str);
            }
        });

        mWindowView.findViewById(R.id.text_connect).setOnClickListener(v -> {
            if (deviceList.get(0) instanceof UsbDevice) {
                mUSBMonitor.requestPermission((UsbDevice) deviceList.get(0));
                //判断是否显示组件
            }
        });


        mCaptureButtonFirst.setOnClickListener(v -> {

        });
        mCaptureButtonFirst.setVisibility(View.INVISIBLE);

        mWindowManager.addView(mWindowView, wmParams);


        frameCamer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    //按下鼠标的时候记录下屏幕的位置
                    case MotionEvent.ACTION_DOWN:
                        mStartX = (int) event.getRawX();
                        mStartY = (int) event.getRawY();

                        break;
                    case MotionEvent.ACTION_MOVE:
                        mEndX = (int) event.getRawX();
                        mEndY = (int) event.getRawY();
                        if (needIntercept()) {
                            //getRawX是触摸位置相对于整个屏幕的位置，getX是控触摸点相对于控件最左边的位置
                            wmParams.x = (int) event.getRawX() - mWindowView.getMeasuredWidth() / 2;
                            wmParams.y = (int) event.getRawY() - mWindowView.getMeasuredHeight() / 2;
                            mWindowManager.updateViewLayout(mWindowView, wmParams);
                            return true;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (needIntercept()) {
                            return true;
                        }
                        break;
                }

                return false;
            }
        });
        frameCamer.setOnClickListener(v -> {
            Log.i(TAG, "点击了");
            if (isAppAtBackground(WindowService.this)) {
                Intent intent = new Intent(WindowService.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        //关闭服务
        button_end.setOnClickListener(view -> {
            dataCallback.unService();
        });
    }


    /**
     * 判断当前应用是前台还是后台
     */
    private boolean isAppAtBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否拦截，根据滑动的距离
     *
     * @return
     */
    private boolean needIntercept() {
        if (Math.abs(mStartX - mEndX) > 30 || Math.abs(mStartY - mEndY) > 30) {
            return true;
        }
        return false;
    }


    private final USBMonitor.OnDeviceConnectListener mOnDeviceConnectListener = new USBMonitor.OnDeviceConnectListener() {
        @Override
        public void onAttach(final UsbDevice device) {
            Log.d("zdl", "========onAttach======");
            Toast.makeText(WindowService.this, "USB_DEVICE_ATTACHED", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onConnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock, final boolean createNew) {
            Log.d("zdl", "========onConnect======");
            Toast.makeText(WindowService.this, "设备连接成功", Toast.LENGTH_SHORT).show();
//            //设备连接成功
            if (!mHandlerFirst.isOpened()) {
                mHandlerFirst.open(ctrlBlock);
                final SurfaceTexture st = mUVCCameraViewFirst.getSurfaceTexture();
                mHandlerFirst.startPreview(new Surface(st));
            }
        }

        @Override
        public void onDisconnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock) {
            Log.d("zdl", "========onDisconnect======");
            Toast.makeText(WindowService.this, "onDisconnect:" + device, Toast.LENGTH_SHORT).show();
//            if ((mHandlerFirst != null) && !mHandlerFirst.isEqual(device)) {
//                queueEvent(new Runnable() {
//                    @Override
//                    public void run() {
//                        mHandlerFirst.close();
//                        if (mFirstPreviewSurface != null) {
//                            mFirstPreviewSurface.release();
//                            mFirstPreviewSurface = null;
//                        }
////                        setCameraButton();
//                    }
//                }, 0);
//            }
        }

        @Override
        public void onDettach(final UsbDevice device) {
            Log.d("zdl", "========onDettach======");
            Toast.makeText(WindowService.this, "USB_DEVICE_DETACHED:" + device, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(final UsbDevice device) {
            Log.d("zdl", "========onCancel======");
            Toast.makeText(WindowService.this, "onCancel:" + device, Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWindowView != null) {
            //移除悬浮窗口
            Log.i(TAG, "removeView");
            mWindowManager.removeView(mWindowView);
        }
        Log.i(TAG, "onDestroy");
    }

    DataCallback dataCallback = null;

    public DataCallback getDataCallback() {
        return dataCallback;
    }

    public void setDataCallback(DataCallback dataCallback) {
        this.dataCallback = dataCallback;
    }

    public interface DataCallback {
        void dataChanged(CameraViewInterface cameraViewInterface);

        void unService();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public class MyBinder extends Binder {
        public WindowService getService() {
            return WindowService.this;
        }
    }

}